package com.jxt.myjxtmanager.okHttp;

import android.content.Context;
import android.os.Build;
import android.widget.Toast;

import com.jxt.myjxtmanager.R;
import com.jxt.myjxtmanager.utils.Config;
import com.jxt.myjxtmanager.utils.LogUtils.LogInfo;
import com.jxt.myjxtmanager.utils.PackageUtils;
import com.jxt.myjxtmanager.utils.SharePreferenceUtils.SharedPrefUtil;
import com.jxt.myjxtmanager.utils.SystemInfo;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.TreeMap;


/**
 * Created by Administrator on 2016/3/4.
 * <p/>
 * 测试 当前
 */
public class AsyncHttpFile {

    /**
     * 修改头像
     */
    private final String API_UPLOAD_HEAD_IMAGE = "/crm/uploadSaleAvatar";
    private static OkHttpClient client = new OkHttpClient();
    private static AsyncHttpFile mInstance;


    public static AsyncHttpFile getInstance() {
        synchronized (HttpClient.class) {
            if (mInstance == null) {
                mInstance = new AsyncHttpFile();
            }
        }
        return mInstance;
    }


    public void updateHttpFile(Context context, File file) {
        TreeMap<String, String> mParam = new TreeMap<String, String>();
        mParam.put("filestr", "hah");
        deliveryResult(context, buildMultipartFormRequest(context, API_UPLOAD_HEAD_IMAGE, mParam, "avatar_img", file));
    }

    private void deliveryResult(final Context cxt, Request request) {
        if (!SystemInfo.isNetworkConnected(cxt)) {
            Toast.makeText(cxt,
                    cxt.getString(R.string.toast_not_network), Toast.LENGTH_SHORT).show();
            return;
        }
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                LogInfo.d("-----------------------> onFailure： " + request.toString());
            }

            @Override
            public void onResponse(final Response response) {
                try {
                    LogInfo.d("-----------------------> onResponse: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private Request buildMultipartFormRequest(Context cxt, String url, TreeMap<String, String> mParam, String fileKey, File file) {
        MultipartBuilder builder = new MultipartBuilder() // bylv--Android 使用OKhttp 3.0以上版本上传文件或图片（MultipartBuilder已不可用）
                .type(MultipartBuilder.FORM);
        Iterator<String> iter = mParam.keySet().iterator();
        String key;
        while (iter.hasNext()) {
            key = iter.next();
//            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
//                    RequestBody.create(null, String.valueOf(mParam.get(key))));
            builder.addFormDataPart(key, String.valueOf(mParam.get(key)));
        }

        if (file != null) {
            String fileName = file.getName();
            RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addFormDataPart(fileKey, fileName, fileBody);
            //TODO 根据文件名设置contentType
//            builder.addPart(Headers.of("Content-Disposition",
//                            "form-data; name=\"" + fileKey + "\"; filename=\"" + fileName + "\""),
//                    fileBody);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String uuid = SystemInfo.getIMEI(cxt);
        String version = PackageUtils.getAppVersion(cxt);
        Request request = new Request.Builder()
                .url(HttpClient.API_BASE_DOCTOR+url)
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .addHeader("Accept", "application/vnd.github.v3+json")
                .addHeader("X-VERSION", version)
                .addHeader("X-VerName", version)
                .addHeader("X-VerCode", version)
                .addHeader("X-Platform", Config.PLATFORM)
                .addHeader("X-Device", Build.DEVICE)
                .addHeader("X-Uuid", uuid)
                .addHeader("X-BuildVersion", Build.VERSION.RELEASE)
                .addHeader("timestamp", timestamp)
                .addHeader("signature", URLEncodedUtils.format(mParam, HTTP.UTF_8))
                .addHeader("token", SharedPrefUtil.getInstance(cxt).getString(Config.SHARED_TOKEN, ""))
                .post(builder.build())
                .build();
        return request;
    }


    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

}
